#!/usr/bin/env python
# fetch and parse xiami album json info, use eyeD3 to update mp3 tag

import sys,json
jf=open(sys.argv[1])
j=json.load(jf)
jf.close()

try:
  open(j['album']['album_id']+'.jpg')
except:
  import urllib
  urllib.urlretrieve(j['album']['album_logo'].replace('_2',''), j['album']['album_id']+'.jpg')

import eyeD3
slst=j['album']['songs']
# total is all tracks for multi-disc album. json has no info.
# can go through songs with same cd_serial to count, may not worth the trouble
total=len(slst) 
for s in slst:
  sid=s['location'].split('/')[-1][:2]
  print s['album_id'], sid, s['artist_name'].encode('utf8'), s['title'].encode('utf8'), s['name'].encode('utf8')
  if s['cd_count'] == '1':
    tag=eyeD3.Tag(s['album_id']+'-'+sid+'.mp3')
  else:
    tag=eyeD3.Tag(s['album_id']+'-'+s['cd_serial']+'-'+sid+'.mp3')
  tag.do_tdtg=False
  tag.header.setVersion(eyeD3.ID3_V2_4)
  tag.setTextEncoding(eyeD3.frames.UTF_8_ENCODING)
  tag.setArtist(s['artist_name'])
  tag.setAlbum(s['title'])
  tag.setTitle(s['name'])
  tag.setTrackNum((int(sid), total))
  if s['cd_count'] != '1':
    tag.setDiscNum((int(s['cd_serial']), int(s['cd_count'])))

  tag.addImage(eyeD3.frames.ImageFrame.FRONT_COVER, s['album_id']+'.jpg')
  tag.update()
